package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.CourseGoodReviewBean;
import com.atguigu.realtime.bean.CourseReviewBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @auther yuzehua
 * @date 2022/10/28 - 15:54
 */
public class Dws_CourseGoodReview extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_CourseGoodReview().init(
                2070,
                2,
                "Dws_CourseGoodReview",
                Constant.TOPIC_DWD_REVIEW_INFO
        );
    }
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1.封装POJO
        SingleOutputStreamOperator<CourseGoodReviewBean> beanStream = parseToPojo(stream);
        // 2.开窗聚合
        SingleOutputStreamOperator<CourseGoodReviewBean> resultStream = windowAndAgg(beanStream);
        resultStream.print();
        // 3. 写出到 clickhouse 中
        writeToClickhouse(resultStream);
    }

    private void writeToClickhouse(SingleOutputStreamOperator<CourseGoodReviewBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_course_good_review_view_window",CourseGoodReviewBean.class));
    }

    private SingleOutputStreamOperator<CourseGoodReviewBean> windowAndAgg(SingleOutputStreamOperator<CourseGoodReviewBean> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<CourseGoodReviewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner(new SerializableTimestampAssigner<CourseGoodReviewBean>() {
                                    @Override
                                    public long extractTimestamp(CourseGoodReviewBean element, long recordTimestamp) {
                                        return element.getTs();
                                    }
                                })
                )
                .keyBy(CourseGoodReviewBean::getCourseId)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<CourseGoodReviewBean>() {
                    @Override
                    public CourseGoodReviewBean reduce(CourseGoodReviewBean value1, CourseGoodReviewBean value2) throws Exception {
                        value1.setUserReviewCount(value1.getUserReviewCount() + value2.getUserReviewCount());
                        value1.setGReviewUserCount(value1.getGReviewUserCount() + value2.getGReviewUserCount());
                        return value1;
                    }
                }, new ProcessWindowFunction<CourseGoodReviewBean, CourseGoodReviewBean, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context ctx, Iterable<CourseGoodReviewBean> elements, Collector<CourseGoodReviewBean> out) throws Exception {
                        CourseGoodReviewBean bean = elements.iterator().next();
                        Long gReviewUserCount = bean.getGReviewUserCount();
                        if(gReviewUserCount != 0){
                            bean.setGoodReview(((double) bean.getUserReviewCount() / (double) gReviewUserCount));
                        }
                        // 补充窗口开始和结束
                        bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));

                        // 表示这个结果的统计时间
                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
                    }
                });
    }

    private SingleOutputStreamOperator<CourseGoodReviewBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(bean -> bean.getString("user_id"))
                .map(new RichMapFunction<JSONObject, CourseGoodReviewBean>() {
                    private ValueState<String> dateState;
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        // 给状态设置ttl
                        ValueStateDescriptor<String> desc = new ValueStateDescriptor<>("dateState", String.class);
                        desc.enableTimeToLive(new StateTtlConfig.Builder(org.apache.flink.api.common.time.Time.days(1)).build());
                        dateState = getRuntimeContext().getState(desc);
                    }

                    @Override
                    public CourseGoodReviewBean map(JSONObject obj) throws Exception {
                        Long ts = AtguiguUtil.toShootTime(obj.getString("create_time"));
                        String courseId = obj.getString("course_id");
                        Long reviewStars = obj.getLong("review_stars");
                        String userId = obj.getString("user_id");

                        Long userReviewCount = 0L;
                        Long gReviewUserCount = 0L;
                        String date = dateState.value();
                        String today = AtguiguUtil.toDate(ts);
                        if (!today.equals(date)) {
                            // 更新状态
                            dateState.update(today);
                            userReviewCount = 1L;
                            if(reviewStars == 5){
                                gReviewUserCount = 1L;
                            }
                        }

                        // 用户当天第一次没给好评，但是后面某次给了好评
                        if(reviewStars == 5){
                            gReviewUserCount = 1L;
                        }

                        return new CourseGoodReviewBean(
                                "","",courseId,userReviewCount,gReviewUserCount,0D,ts
                        );
                    }
                });
    }
}
